package com.mini.service;

import com.alibaba.fastjson.JSONObject;
import com.mini.client.MiniQweibServer;
import com.mini.client.TeacherRelationVO;
import com.mini.client.WehubAdminClient;
import com.mini.constant.RedisKeyConst;
import com.mini.model.BusinessTeacherInfo;
import com.mini.model.BusinessTeacherWechatInfo;
import com.mini.repository.BusinessTeacherWechatInfoRepository;
import com.mini.req.CorpSetAddUserRemark;
import com.mini.req.CorpWxInfoREQ;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author zhangxiaobin
 * @title: BusinessTeacherWechatInfoService
 * @description: TODO
 * @date 2020/3/2315:13
 */
@Service
@Slf4j
public class BusinessTeacherWechatInfoService extends BaseService {

    private static final Integer useState = 0;

    private static final Integer unUseState = 1;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private BusinessTeacherWechatInfoRepository repository;

    @Autowired
    private MiniQweibServer miniQweibServer;


    @Autowired
    private BusinessTeacherInfoService teacherInfoService;

    @Autowired
    private WehubAdminClient wehubAdminServer;

    public void save(BusinessTeacherWechatInfo teacherWechatInfo) {
        if (teacherWechatInfo.getUseType() == null) {
            teacherWechatInfo.setUseType(0);
        }
        repository.save(teacherWechatInfo);
        deleteCache(teacherWechatInfo.getTeacherId());
    }

    public void saveCorpWx(Long teacherId, String teacherName, CorpWxInfoREQ syncTeacherREQ){
        String corpId = syncTeacherREQ.getCorpId();
        String corpName = syncTeacherREQ.getCorpName();
        String corpUserId = syncTeacherREQ.getCorpUserId();
        String corpUserName = syncTeacherREQ.getCorpUserName();
        String corpNewUserId = syncTeacherREQ.getCorpNewUserId();
        String corpUserQrUrl = syncTeacherREQ.getCorpUserQrUrl();
        String teacherPhoneNum = syncTeacherREQ.getTeacherPhoneNum();
        String corpUserAvatar = syncTeacherREQ.getCorpUserAvatar();
        Integer userType = syncTeacherREQ.getUseType();

        BusinessTeacherWechatInfo teacherWechatInfoFromDB = findByTeacherIdAndWxNo(teacherId, corpUserId);
        if(teacherWechatInfoFromDB != null && !(corpUserId.equalsIgnoreCase(corpNewUserId))){
            BusinessTeacherWechatInfo wechatInfo = new BusinessTeacherWechatInfo();
            if(2 == userType.intValue()) {
                wechatInfo.setTeacherId(teacherId);
                wechatInfo.setTeacherName(teacherName);
                wechatInfo.setCreateTime(teacherWechatInfoFromDB.getCreateTime());
                wechatInfo.setCreateUser(teacherWechatInfoFromDB.getCreateUser());
                wechatInfo.setWxNo(corpNewUserId);
                wechatInfo.setOrders(teacherWechatInfoFromDB.getOrders());
                wechatInfo.setUpdateUser(teacherId);
                wechatInfo.setUpdateTime(new Date());
                wechatInfo.setWxQrUrl(corpUserQrUrl);
                wechatInfo.setPhone(teacherPhoneNum);
                wechatInfo.setStates(teacherWechatInfoFromDB.getStates());
                wechatInfo.setUseType(teacherWechatInfoFromDB.getUseType());
                wechatInfo.setCorpUserId(corpNewUserId);
                wechatInfo.setCorpId(corpId);
                wechatInfo.setUseType(userType);
                wechatInfo.setCorpName(corpName);
                wechatInfo.setCorpUserName(corpUserName);
                wechatInfo.setCorpUserQrUrl(corpUserQrUrl);
                wechatInfo.setCorpUserAvatar(corpUserAvatar);
            }else {
                wechatInfo.setTeacherId(teacherId);
                wechatInfo.setTeacherName(teacherName);
                wechatInfo.setCreateTime(teacherWechatInfoFromDB.getCreateTime());
                wechatInfo.setCreateUser(teacherWechatInfoFromDB.getCreateUser());
                wechatInfo.setWxNo(corpNewUserId);
                wechatInfo.setOrders(teacherWechatInfoFromDB.getOrders());
                wechatInfo.setUpdateUser(teacherId);
                wechatInfo.setUpdateTime(new Date());
                wechatInfo.setWxQrUrl(corpUserQrUrl);
                wechatInfo.setPhone(teacherPhoneNum);
                wechatInfo.setStates(teacherWechatInfoFromDB.getStates());
                wechatInfo.setUseType(userType);
            }
            deleteWx(teacherWechatInfoFromDB);
            repository.save(wechatInfo);

            //初始化备注
//            saveUserRemark(wechatInfo);

            return;
        }
//        boolean init = false;
        if(teacherWechatInfoFromDB == null){
            teacherWechatInfoFromDB = new BusinessTeacherWechatInfo();
            teacherWechatInfoFromDB.setCreateTime(new Date());
            teacherWechatInfoFromDB.setCreateUser(teacherId);
            teacherWechatInfoFromDB.setOrders(findMaxOrdersByTeacherId(teacherId) + 1);
            teacherWechatInfoFromDB.setWxNo(corpUserId);
            teacherWechatInfoFromDB.setStates(0);//默认新增启用
            teacherWechatInfoFromDB.setTeacherId(teacherId);
            teacherWechatInfoFromDB.setTeacherName(teacherName);
            teacherWechatInfoFromDB.setUseType(2);
            teacherWechatInfoFromDB.setCorpUserQrUrl(corpUserQrUrl);
//            init = true;
        }
        teacherWechatInfoFromDB.setStates(syncTeacherREQ.getStates());
        teacherWechatInfoFromDB.setCorpUserAvatar(corpUserAvatar);
        teacherWechatInfoFromDB.setUpdateUser(teacherId);
        teacherWechatInfoFromDB.setUpdateTime(new Date());
        teacherWechatInfoFromDB.setWxQrUrl(corpUserQrUrl);
        teacherWechatInfoFromDB.setCorpId(corpId);
        teacherWechatInfoFromDB.setCorpName(corpName);
        teacherWechatInfoFromDB.setCorpUserId(corpUserId);
        teacherWechatInfoFromDB.setCorpUserName(corpUserName);
        teacherWechatInfoFromDB.setPhone(teacherPhoneNum);
        teacherWechatInfoFromDB.setUseType(userType);
        repository.save(teacherWechatInfoFromDB);
//        if(init){
//            //初始化备注
//
//        }
        deleteCache(teacherId);
    }

    public void save(Long teacherId,
                     String teacherName,
                     String wxNo,
                     String qrUrl,
                     String phone,
                     Long userId,
                     String wxNewNo,
                     Integer useType) {
        BusinessTeacherWechatInfo teacherWechatInfoFromDB = findByTeacherIdAndWxNo(teacherId, wxNo);
        if (teacherWechatInfoFromDB != null && !(wxNewNo.equalsIgnoreCase(wxNo))) {
            BusinessTeacherWechatInfo wechatInfo = new BusinessTeacherWechatInfo();
            wechatInfo.setTeacherId(teacherId);
            wechatInfo.setTeacherName(teacherName);
            wechatInfo.setCreateTime(teacherWechatInfoFromDB.getCreateTime());
            wechatInfo.setCreateUser(teacherWechatInfoFromDB.getCreateUser());
            wechatInfo.setWxNo(wxNewNo);
            wechatInfo.setOrders(teacherWechatInfoFromDB.getOrders());
            wechatInfo.setUpdateUser(userId);
            wechatInfo.setUpdateTime(new Date());
            wechatInfo.setWxQrUrl(qrUrl);
            wechatInfo.setPhone(phone);
            wechatInfo.setStates(teacherWechatInfoFromDB.getStates());
            wechatInfo.setUseType(useType);
            repository.save(wechatInfo);
            deleteWx(teacherWechatInfoFromDB);
            return;
        }

        if (teacherWechatInfoFromDB == null) {
            teacherWechatInfoFromDB = new BusinessTeacherWechatInfo();
            teacherWechatInfoFromDB.setCreateTime(new Date());
            teacherWechatInfoFromDB.setCreateUser(userId);
            teacherWechatInfoFromDB.setOrders(findMaxOrdersByTeacherId(teacherId) + 1);
            teacherWechatInfoFromDB.setWxNo(wxNo);
            teacherWechatInfoFromDB.setStates(0);//默认新增启用
            teacherWechatInfoFromDB.setTeacherId(teacherId);
            teacherWechatInfoFromDB.setTeacherName(teacherName);
            teacherWechatInfoFromDB.setUseType(useType);
        }
        teacherWechatInfoFromDB.setUseType(useType);
        teacherWechatInfoFromDB.setUpdateUser(userId);
        teacherWechatInfoFromDB.setUpdateTime(new Date());
        teacherWechatInfoFromDB.setWxQrUrl(qrUrl);
        teacherWechatInfoFromDB.setPhone(phone);
        repository.save(teacherWechatInfoFromDB);
        deleteCache(teacherId);
    }

    public Long countByWxNoAndTeacherIdNot(String WxNo, Long teacherId) {
        return repository.countByWxNoAndTeacherIdNot(WxNo, teacherId);
    }

    public BusinessTeacherWechatInfo findByWxNo(String wxNo) {
        BusinessTeacherWechatInfo info = repository.findByWxNo(wxNo);
        return info;
    }

    public BusinessTeacherWechatInfo findByTeacherIdAndWxNo(Long teacherId, String wxNo) {
        BusinessTeacherWechatInfo info = repository.findByTeacherIdAndWxNo(teacherId, wxNo);
        return info;
    }

    /**
     * 查询启用的老师的微信信息列表
     *
     * @param teacherId
     * @return
     */
    public List<BusinessTeacherWechatInfo> findCanUseWechatByTeacherId(Long teacherId, Integer useType) {
        String teacherWechatInfoListKey = "";
        if (useType == null) {
            teacherWechatInfoListKey = RedisKeyConst.getTeacherWechatInfoList(teacherId);
        } else if (useType == 0) {
            teacherWechatInfoListKey = RedisKeyConst.getTeacherWechatInfoList(teacherId, useType);
        }
        Object o = redisTemplate.opsForValue().get(teacherWechatInfoListKey);
        if (o == null) {
            List<BusinessTeacherWechatInfo> canUseTeacherWechatInfos = new ArrayList<>();
            List<BusinessTeacherWechatInfo> teacherWechatInfos = findByTeacherId(teacherId, useType);
            if (teacherWechatInfos != null) {
                for (BusinessTeacherWechatInfo wechatInfo : teacherWechatInfos) {
                    Integer states = wechatInfo.getStates();
                    if (states != null && states.intValue() == 0) {
                        canUseTeacherWechatInfos.add(wechatInfo);
                    }
                }
            }
            redisTemplate.opsForValue().set(teacherWechatInfoListKey, canUseTeacherWechatInfos, 7, TimeUnit.DAYS);
            return canUseTeacherWechatInfos;
        }
        return (List<BusinessTeacherWechatInfo>) o;
    }

    /**
     * 查询所有的老师的微信信息列表
     *
     * @param teacherId
     * @return
     */
    public List<BusinessTeacherWechatInfo> findByTeacherId(Long teacherId, Integer useType) {
        List<BusinessTeacherWechatInfo> teacherWechatInfos = new ArrayList<>();
        if (useType == null) {
            teacherWechatInfos = repository.findByTeacherIdOrderByOrdersAsc(teacherId);
        } else {
            teacherWechatInfos = repository.findByTeacherIdAndUseTypeOrderByOrdersAsc(teacherId, useType);
        }
        return teacherWechatInfos;
    }

    /**
     * 查询老师的微信信息列表
     *
     * @param teacherId
     * @return
     */
    public List<BusinessTeacherWechatInfo> findWechatListByTeacherId(Long teacherId, Integer useType) {
        List<BusinessTeacherWechatInfo> teacherWechatInfos = new ArrayList<>();
        teacherWechatInfos = repository.findByTeacherIdAndUseTypeOrderByOrdersAsc(teacherId, useType);
        return teacherWechatInfos;
    }

    @Transactional
    public void updateWechatNoStates(Long teacherId, String wxNo, Integer states, BusinessTeacherInfo teacherInfo) {
        try {
            repository.updateWechatStates(teacherId, wxNo, states);
            deleteCache(teacherId);
            if (states.equals(0)) {
                teacherInfo.setStates(0);
//                teacherInfo.setAddWechatNum(0);
                teacherInfoService.save(teacherInfo);
            }
        } catch (Exception ex) {
            log.error("updateWechatNoStates error ,ex = {} ", ex);
        }
    }

    public Long findMaxOrdersByTeacherId(Long teacherId) {
        Long aLong = repository.findMaxOrdersByTeacherId(teacherId);
        if (aLong == null) {
            return 0L;
        }
        return aLong;
    }


    @Transactional
    public void deleteTeacherAllWechatNo(Long teacherId) {
        repository.deleteByTeacherId(teacherId);
        deleteCache(teacherId);
    }

    @Transactional
    public boolean deleteTeacherWechatNo(Long teacherId, List<String> wxNo) {
        repository.deleteByTeacherIdAndWxNoIn(teacherId, wxNo);
        Long n = repository.countByTeacherIdAndStates(teacherId, 0);
        if (n == 0) {
            return true;
        }
        deleteCache(teacherId);
        return false;
    }


    public BusinessTeacherWechatInfo findCorpWxInfoByTeacherId(Long teacherId) {
        BusinessTeacherWechatInfo businessTeacherWechatInfo = repository.findByTeacherIdAndUseType(teacherId, 2);
        return businessTeacherWechatInfo;
    }

    public Long countByCorpUserIdAndTeacherIdNot(String corpUserId, Long teacherId) {
        return repository.countByCorpUserIdAndTeacherIdNot(corpUserId, teacherId);
    }

    public BusinessTeacherWechatInfo findByTeacherIdAndCorpUserId(Long teacherId, String corpUserId) {
        return repository.findByTeacherIdAndCorpUserId(teacherId, corpUserId);
    }

    private void deleteCache(Long teacherId) {
        redisTemplate.delete(RedisKeyConst.getTeacherInfo(teacherId));
        redisTemplate.delete(RedisKeyConst.getTeacherWechatInfoList(teacherId));
        redisTemplate.delete(RedisKeyConst.getTeacherWechatInfoList(teacherId, 0));
        redisTemplate.delete(RedisKeyConst.getTeacherWechatInfoList(teacherId, 1));
        redisTemplate.delete(RedisKeyConst.getTeacherWechatInfoList(teacherId, 2));
        redisTemplate.delete(RedisKeyConst.getTeacherWechatInfoList(teacherId, "apply"));
    }

    public List<BusinessTeacherWechatInfo> findWehubCanUseWechatByTeacherId(Long teacherId) {
        List<Integer> useTypes = new ArrayList<>();
        useTypes.add(0);
        useTypes.add(1);
        List<BusinessTeacherWechatInfo> teacherWechatInfos = repository.findByTeacherIdAndUseTypeInOrderByOrdersAsc(teacherId, useTypes);
        return teacherWechatInfos;
    }

    //删除微信、解绑企业微信
    private void deleteWx(BusinessTeacherWechatInfo wechatInfo) {
        Integer useType = wechatInfo.getUseType();
        Long teacherId = wechatInfo.getTeacherId();
        String wxNo = wechatInfo.getWxNo();
        repository.delete(wechatInfo);
        //删除企业微信，同步删除欢迎语、备注
        if(useType != null && 2 == useType.intValue()){
            deleteWelcomAndRemarkSet(wechatInfo.getCorpId(),wechatInfo.getCorpUserId());
        }
        deleteCache(teacherId);
        wehubAdminServer.disableWechat(reqSign, teacherId,null, wxNo);
    }

    /**
     * 根据老师id删除所有问题
     *
     * @param teacherId
     */
    public void deleteAllCorpInfo(Long teacherId) {
        List<BusinessTeacherWechatInfo> teacherWechatInfos = findByTeacherId(teacherId, 2);
        if (teacherWechatInfos != null && teacherWechatInfos.size() > 0) {
            for (BusinessTeacherWechatInfo wechatInfo : teacherWechatInfos) {
                Integer useType = wechatInfo.getUseType();
                //删除企业微信，同步删除欢迎语、备注
                if (useType != null && 2 == useType.intValue()) {
                    deleteWelcomAndRemarkSet(wechatInfo.getCorpId(), wechatInfo.getCorpUserId());
                }
            }
        }
    }

    /**
     * 根据微信号删除
     *
     * @param wxNo
     */
    public void deleteCorpInfo(String wxNo) {
        BusinessTeacherWechatInfo wechatInfo = repository.findByWxNo(wxNo);
        if(wechatInfo != null) {
            Integer useType = wechatInfo.getUseType();
            //删除企业微信，同步删除欢迎语、备注
            if (useType != null && 2 == useType.intValue()) {
                deleteWelcomAndRemarkSet(wechatInfo.getCorpId(), wechatInfo.getCorpUserId());
            }
        }
    }

    private void deleteWelcomAndRemarkSet(String corpId,String corpUserId){
        TeacherRelationVO teacherRelationVO = new TeacherRelationVO();
        teacherRelationVO.setCorpId(corpId);
        teacherRelationVO.setTeacherConcatId(corpUserId);
        miniQweibServer.unRelationTeacher(reqSign,teacherRelationVO);
    }

    /**
     * 根据加微状态，获取老师ID
     *
     * @param teacherIds
     * @param state
     * @return
     */
    public List<Long> getTeacherIds(List<Long> teacherIds, Integer state) {

        List<BusinessTeacherWechatInfo> teacherWechatInfos = repository.findByTeacherIdInAndStates(teacherIds, state);

        if (!CollectionUtils.isEmpty(teacherWechatInfos)) {
            return teacherWechatInfos.stream()
                    .map(BusinessTeacherWechatInfo::getTeacherId)
                    .distinct()
                    .collect(Collectors.toList());
        }
        return null;
    }

    /**
     * 检查老师微信是否解绑或禁用 true 解绑/禁用  false:未
     *
     * @param teacherId
     * @return
     */
    public boolean checkTeacher(Long teacherId) {
        boolean falg = true;
        List<BusinessTeacherWechatInfo> teacherWechatInfos = repository.findByTeacherIdOrderByOrdersAsc(teacherId);
        if (CollectionUtils.isEmpty(teacherWechatInfos)) {
            falg = true;
        } else {
            for (BusinessTeacherWechatInfo wechatInfo : teacherWechatInfos) {
                Integer state = wechatInfo.getStates();
                if (state.equals(0)) {
                    falg = false;
                    break;
                }
            }
        }
        return falg;
    }
}
